package br.unirn.exemplos.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.unirn.exemplos.dao.PostDao;
import br.unirn.exemplos.dao.UsuarioDao;
import br.unirn.exemplos.dominio.Post;
import br.unirn.exemplos.dominio.Usuario;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String operacao = request.getParameter("operacao");

		if (operacao.equals("logar")) {

			String login = request.getParameter("login");
			String senha = request.getParameter("senha");

			UsuarioDao dao = new UsuarioDao();
			PostDao pDao = new PostDao();
			try{
				if (login != null ){
					Usuario usuario =  dao.findByLogin(login);
					//senha com base em hash, para evitar ficar em claro.
					if (usuario.getSenha().equals(String.valueOf(senha))) {
						HttpSession session = request.getSession(true);

						session.setAttribute("usuarioLogado", usuario);
						//atualiza posts j� para exibi��o inicial da timeline
						List<Post> posts = pDao.findPosts((Usuario) session.getAttribute("usuarioLogado"));
						session.setAttribute("tweets", posts);
						
						loginComSucesso(request, response);
					}else{
						loginSemSucesso(response);		
					}

				}else{
					loginSemSucesso(response);
					
				}
				return;
			}finally{
				if (dao!=null)
					dao.close();
				if (pDao!=null)
					pDao.close();
			}
		} else if (operacao.equals("logout")) {
			HttpSession session = request.getSession(false);
			if (session != null) {
				session.invalidate();
			}
			response.sendRedirect(request.getContextPath() + "/index.jsp");
		}
		return;
		// response.sendRedirect(request.getContextPath()+"/index.html");

	}

	private void loginSemSucesso(HttpServletResponse response)
			throws IOException {
		PrintWriter out = response.getWriter();

		out.write("<html>");
		out.write("<body>");
		out.write("<h1>Senha Incorreta!</h1>");
		out.write("</body>");
		out.write("</html>");

		out.close();

	}
	
	private void loginComSucesso(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		response.sendRedirect(request.getContextPath()+"/sistema/timeline.jsp");
		return;
	}

}
